package com.chapter_4;

import java.io.BufferedOutputStream;
import java.util.concurrent.TimeoutException;

/**
 * @Author: Timo
 * @Date: 2019/5/15 14:08
 * @Description: guarded timed
 */
public class Host {
    private final long timeout;
    private boolean ready = false;

    public Host(long timeout) {
        this.timeout = timeout;
    }

    /**
     * 修改状态
     */
    public synchronized void setExecutable() {
        ready = Boolean.TRUE;
        // 唤起所有等待中得线程
        notifyAll();
    }


    /**
     * 执行
     * @throws TimeoutException
     * @throws InterruptedException
     */
    public synchronized void execute() throws TimeoutException, InterruptedException {
        long start = System.currentTimeMillis();
        // 判断当前是否已读
        while (!ready) {
            long now = System.currentTimeMillis();
            long rest = timeout - (now - start);
            if (rest <= 0) {
                throw new TimeoutException("now - start = " + (now - start) + ", timeou t = "+ timeout);
            }
            wait(rest);

        }
        doExecute();
    }

    private void doExecute() {
        System.out.println(Thread.currentThread().getName() + "calls doExecute ");
    }
}
